<?php
namespace app\common\service;

use app\album\model\Album as AlbumModel;
use think\Db;

class Album
{
    public function __construct()
    {
//        if (empty($this->user_id = session('users.user_id'))) {
//            $data = UsersModel::get(['wechat_openid' => session('users.user_openid')]);
//            $this->user_id = $data['users_id'];
//            session('users.user_id', $data['users_id']);
//        }
        $this->activity_id = session('activity_id.id');
    }

    public function add($img_url,$userId)
    {
        $data = [
            'm_id' => $userId['users_id'],
            'img_url' => $img_url,
            'activity_id' => $this->activity_id,
        ];

//        if ($old_data = AlbumModel::get(['m_id' => $this->user_id])) {
//            $old_data->img_url = $img_url;
//            if ($old_data->save()) {
//                return true;
//            } else {
//                return false;
//            }
//        } else {
//            if (AlbumModel::create($data)) {
//                return true;
//            }
//        }

        if (AlbumModel::create($data)) {
            return true;
        }

        return false;
    }

    public function getImgUrl()
    {
        $data = AlbumModel::get(['m_id' => $this->user_id]);
        if (empty($data)) {
            return false;
        }
        return $data['img_url'];
    }
    public function downloadImage($url, $path = 'static/upload/frames/')
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $file = curl_exec($ch);
        curl_close($ch);
        $filename = pathinfo($url, PATHINFO_BASENAME);
        $resource = fopen($path . $filename, 'a');
        fwrite($resource, $file);
        fclose($resource);
    }
    public function getLocalImgPath($fileurl){
        preg_match('/\/([^\/]+\.[a-z]+)[^\/]*$/',$fileurl,$match);
        return '/static/upload/frames/'.$match[1];
    }
    public function baseEncode($base){
        $base64_string= explode(',',$base['base64']);
        $result = base64_decode($base64_string[1]);
        return $result;
    }

    public function iphoneImg($img_url){
        $exif = exif_read_data($img_url);
        $image = imagecreatefromjpeg($img_url);
        if(!empty($exif['Orientation'])){
            if($exif['Orientation'] == 3) {
                $result = imagerotate($image, 180, 0);
                imagejpeg($result, $img_url,100);
            } elseif($exif['Orientation'] == 6) {
                $result = imagerotate($image, -90, 0);
                imagejpeg($result, $img_url, 100);
            } elseif($exif['Orientation'] == 8) {
                $result = imagerotate($image, 90, 0);
                imagejpeg($result, $img_url, 100);
            }
            isset($result) && imagedestroy($result);
            imagedestroy($image);
        }
    }
}